package com.gykfbxxh.imovie.view.main;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.app.utils.util.ToastUtils;
import com.baidu.mobstat.StatService;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.MainFragmentTabAdapter;
import com.gykfbxxh.imovie.base.PermissionRequestActivity;
import com.gykfbxxh.imovie.config.ActivityRequestCode;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.manager.AppConfigManager;
import com.gykfbxxh.imovie.manager.AppManager;
import com.gykfbxxh.imovie.manager.UserInforManager;
import com.gykfbxxh.imovie.videoplayer.JCVideoPlayer;
import com.gykfbxxh.imovie.view.main.fragment.FilmLibraryFragment;
import com.gykfbxxh.imovie.view.main.fragment.MineFragment;
import com.gykfbxxh.imovie.view.main.fragment.RecommendFragment;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.util.ArrayList;

/**
 * Created by xuxinghai
 * On 2017/8/17
 * 主页面
 */
public class MainActivity extends PermissionRequestActivity implements View.OnClickListener {
    private long mExitTime;//最后一次点击的时间
    private LinearLayout main_bottom;
    private View main_home_btn,main_watch_btn,main_mine_btn;
    private ArrayList<Fragment> fragments; // 主页面Fragment集合
    private RecommendFragment mRecommendFragment;//推荐Fragment
    private FilmLibraryFragment mFilmLibraryFragment;//片库Fragment
    private MineFragment mMineFragment;//我的Fragment
    private MainFragmentTabAdapter tabAdapter;// 管理主页面fragment的管理者


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        this.requestWindowFeature(Window.FEATURE_SWIPE_TO_DISMISS);
//        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        //友盟推送,与统计无关,作为日活统计,可以分条件来推送
        if (AppConfigManager.getInstance().readConfig(ConfigKey.option_isPull, true)) {
            PushAgent.getInstance(this).onAppStart();
        }
        setContentView(R.layout.activity_main);
        // 将主界面加入Activity栈管理中
        AppManager.getAppManager().addActivity(this);
        //开始逻辑程序
        startLogic();

    }


    /**
     * 启动逻辑程序
     */
    private void startLogic() {
        initView();//初始化页面控件
        initFragments();//初始化需要展示的页面录
        UserInforManager.getInstance().localWeiLogin(this);//伪登
//        flushMsgDotSum();//刷新消息
//        receiveMsgPush(getIntent());//接收消息推送
//        new CheckVersionUtils().checkVertion(this, false);//检查版本更新
//        EventBus.getDefault().register(this);
//        checkPushPrompt();//检查push红点
//        initRedDot();//刷新右上角红点
//        initLaudAndDefriendList();//初始化点赞列表
    }

    /**
     * 加载需要显示的内容
     */
    private void initFragments() {
        fragments = new ArrayList<>();
        fragments.clear();
        mRecommendFragment = new RecommendFragment();
        fragments.add(mRecommendFragment);
        mFilmLibraryFragment = new FilmLibraryFragment();
        fragments.add(mFilmLibraryFragment);
        mMineFragment = new MineFragment();
        fragments.add(mMineFragment);

        if (fragments != null && !fragments.isEmpty()) {
            tabAdapter = new MainFragmentTabAdapter(getSupportFragmentManager(), fragments, R.id.fl_main_fragment_content, fragments.size());
        }
    }


    /**
     * 初始化页面控件
     */
    private void initView() {
        main_bottom = (LinearLayout)findViewById(R.id.main_bottom);
        main_home_btn = findViewById(R.id.main_home_btn);
        main_watch_btn = findViewById(R.id.main_watch_btn);
        main_mine_btn = findViewById(R.id.main_mine_btn);
        main_home_btn.setSelected(true);
        main_home_btn.setOnClickListener(this);
        main_watch_btn.setOnClickListener(this);
        main_mine_btn.setOnClickListener(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event == null)
            return true;// 防止nullException
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (NiceVideoPlayerManager.instance().onBackPressd()){
                return true;
            }
            if (JCVideoPlayer.backPress()) {
                //判断是否有视频全屏
                return true;
            }
            //如果连续点击的时间大于2秒
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                try {
                    ToastUtils.showText("再按一次退出");
                } catch (NoClassDefFoundError e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mExitTime = System.currentTimeMillis();
            } else {
                try {
                    // System.exit(0);
                    AppManager.getAppManager().AppExit(getApplicationContext());// 退出程序
                } catch (Exception e) {
                }
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            // 拦截MENU按钮点击事件，让他无任何操作
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if(v ==null){
            return;
        }
        switch (v.getId()){
            case R.id.main_home_btn://主页
                if(tabAdapter==null) {
                    return;
                }
                if(tabAdapter.getCurrentTab() == 0) {
                    flushHomePage();
                    return;
                }
                switchTab(v.getId());
                tabAdapter.onChanged(0);

                break;
            case R.id.main_watch_btn://片库
                if(tabAdapter==null) {
                    return;
                }
                switchTab(v.getId());
                tabAdapter.onChanged(1);
                break;
            case R.id.main_mine_btn://我的
                if(tabAdapter==null) {
                    return;
                }
                if(mMineFragment!=null) {
                    mMineFragment.getLikeLookData();
                }
                switchTab(v.getId());
                tabAdapter.onChanged(2);
                break;

        }
    }

    /**
     * 切换底部tab的方法
     * @param btnId
     */
    private void switchTab(int btnId) {
        if(main_bottom ==null) {
            return;
        }
        JCVideoPlayer.releaseAllVideos();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();

        for (int i = 0; i < main_bottom.getChildCount(); i++) {
            if (main_bottom.getChildAt(i) != null && main_bottom.getChildAt(i).getVisibility() == View.VISIBLE) {
                if (main_bottom.getChildAt(i).getId() == btnId) {
                    main_bottom.getChildAt(i).setSelected(true);
                } else {
                    main_bottom.getChildAt(i).setSelected(false);
                }
            }
        }
    }

    /**
     * 首页页面刷新
     */
    private void flushHomePage() {
        //暂停视频
        JCVideoPlayer.releaseAllVideos();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        if (mFilmLibraryFragment != null) {
            mFilmLibraryFragment.flushCurrentPage();
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            JCVideoPlayer.IS_FULLSCREEN = true;
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            JCVideoPlayer.IS_FULLSCREEN = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 百度统计
        StatService.onPause(this);
        //友盟统计
        MobclickAgent.onPause(this);
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //加载用户头像
//        loadUserPic();
        // 百度统计
        StatService.onResume(this);
        //友盟统计
        MobclickAgent.onResume(this);
    }


    /**
     * 跳转到主页片库fragment
     */
    public void goToFilmLibrary() {
        if(tabAdapter==null) {
            return;
        }
        switchTab(R.id.main_watch_btn);
        tabAdapter.onChanged(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityRequestCode.REQEUST_CODE_SET) {
            if(mMineFragment!=null){
                mMineFragment.onActivityResult(requestCode,resultCode,data);
            }
        }
    }
}
